package marketeer;

import general.AuctionOptions;
import general.MarketPlaceMarketeerInterface;
import general.MarketeerClientInterface;
import general.Product;
import general.ProductRecord;

import java.rmi.RemoteException;
import java.util.Iterator;
import java.util.LinkedList;

public class MarketeerClientService implements MarketeerClientInterface {
	
	private MarketPlaceMonitor fMarketPlaceMonitor;
	
	public MarketeerClientService() {
		fMarketPlaceMonitor = new MarketPlaceMonitor();
	}

	public void addProduct(Product product, AuctionOptions auctionOptions) throws RemoteException {
		// Get random marketPlace
		MarketPlaceMarketeerInterface marketPlace = fMarketPlaceMonitor.getRandomMarketPlace();
		
		// Add product request
		marketPlace.addProduct(product, auctionOptions);
	}

	public LinkedList<ProductRecord> searchProducts(String name) throws RemoteException {
		// Create resultList
		LinkedList<ProductRecord> resultList = new LinkedList<ProductRecord>();
		
		// Search all the marketPlaces
		Iterator<MarketPlaceMarketeerInterface> marketPlacesIt = fMarketPlaceMonitor.getMarketPlaces();
		while (marketPlacesIt.hasNext()) {
			MarketPlaceMarketeerInterface marketPlace = marketPlacesIt.next();
			LinkedList<ProductRecord> tempList = marketPlace.searchProducts(name);
			if (!tempList.isEmpty()) {
				Iterator<ProductRecord> it = tempList.iterator();
				while (it.hasNext()) {
					resultList.add(it.next());
				}
			}
		}
		
		// Return list
		return resultList;
	}
}
